package com.gjp.springbootexception.exception;

import com.gjp.springbootexception.bean.ResultVO;
import com.gjp.springbootexception.enums.HttpStatusEnum;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/error")
public class GlobalErrorController implements ErrorController {

    @Override
    public String getErrorPath() {
        return "/error";
    }

    @RequestMapping(produces = {"text/html"})
    public ModelAndView handlerHtmlError(HttpServletRequest request){
        //获取异常状态码
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        //获取异常消息
        String errorMsg = (String)request.getAttribute("javax.servlet.error.message");
        //如果不是我们自己抛出的异常，异常消息会是空字符串，如果是空字符串则用默认错误消息返回
        if (StringUtils.isEmpty(errorMsg)){
            errorMsg = HttpStatusEnum.resolve(statusCode).getReason();
        }
        ModelAndView modelAndView = new ModelAndView("error/"+statusCode);
        modelAndView.addObject("msg",errorMsg);
        return modelAndView;
    }

    @RequestMapping
    public Object handlerOtherError(HttpServletRequest request){
        //获取异常状态码
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        //获取异常消息
        String errorMsg = (String)request.getAttribute("javax.servlet.error.message");
        //如果不是我们自己抛出的异常，异常消息会是空字符串，如果是空字符串则用默认错误消息返回
        if (StringUtils.isEmpty(errorMsg)){
            errorMsg = HttpStatusEnum.resolve(statusCode).getReason();
        }
        ResultVO resultVO = new ResultVO();
        resultVO.setCode(statusCode);
        resultVO.setMsg(errorMsg);
        return resultVO;
    }
}
